
const { EnterpriseModel, EquipmentModel, CabinetModel, EquipmentLogModel } = require('../../models/index')
const koaTool = require('../../commons/koa_tool')
const ObjectId = require("mongoose").Types.ObjectId
const moment = require("moment")

class RptController {

    // 获取企业数据（带有经纬度）
    getEnterData = async (ctx) => {
        
        let query = {
            status: 1,
            lng_lat: {$exists: true}
        }

        let enterDataList = await EnterpriseModel.find(query, "_id name lng_lat").lean();

        koaTool.success(ctx, "获取成功", {
            list: enterDataList
        })

    }

    // 获取设备异常数据
    getAbnormalEquData = async (ctx) => {

        let equQuery = {
            status: 1,
            machine_status: {$ne: 1}, // 异常数据
        }

        let equDataList = await EquipmentModel.find(equQuery, "real_num enterprise_id type gas_type").lean()

        koaTool.success(ctx, "获取成功", {
            list: equDataList
        })
    } 


    // admin
    // 通过设备ID 获取其信息值
    getEquInfoById = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ["id"])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        
        let option = [
            {path: "cabinet_id", select: "name"},
            {path: "enterprise_id", select: "name"}
        ]
        let equData = await EquipmentModel.findById(input.id).populate(option).lean();

        // console.log(equData)
        let resultData = {
            type: equData.type,
            name: equData.name,
            eName: equData.enterprise_id.name,
            cabName: equData.cabinet_id.name
        }

        return koaTool.success(ctx, koaTool.msg.SUCCESS, resultData)

    }

    // 获取设备状态统计
    getEquStatusCount = async (ctx) => {

        let dataList = await EquipmentModel.aggregate([
            {$match: {status: 1}},
            {$group: {
                _id: "$machine_status",
                count: {$sum: 1}
            }}
        ])

        return koaTool.success(ctx, koaTool.msg.SUCCESS, dataList)
    }

    // 获取系统树状数据
    getEquTreeData = async (ctx) => {

        let enterDataList = await EnterpriseModel.find({status: 1}, "_id name lng_lat").sort({_id: -1}).lean();
        let resultData = []
        let proAll = enterDataList.map(async (item, index) => {
            let cabinetList = await CabinetModel.find({status: 1, enterprise_id: item._id}, "_id name").lean()

            let equQuery = {
                status: 1,
                enterprise_id: item._id,
                cabinet_id: {$in: cabinetList.map(cItem => cItem._id)}
            }
            let equipList = await EquipmentModel.find(equQuery, "code type name _id cabinet_id").lean();
            resultData[index] = {
                level: 1,
                label: item.name,
                id: item._id,
                lnglat: item.lng_lat,
                children: cabinetList.map(cItem => {
                    return {
                        label: cItem.name,
                        id: cItem._id,
                        level: 2,
                        children: equipList.filter(eItem => eItem.cabinet_id.toString() == cItem._id.toString()).map(eItem => {
                            return {
                                level: 3,
                                label: `${eItem.name}-[${eItem.code}]`,
                                id: eItem._id
                            }
                        })
                    }
                })
            }
        })

        await Promise.all(proAll);

        return koaTool.success(ctx, koaTool.msg.SUCCESS, resultData)

    }

    // 通过柜号Id 获取对应的设备数据
    getEquLogListByCabId = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ["cabId"])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        let equQuery = {
            status: 1,
            cabinet_id: ObjectId(input.cabId),
            machine_status: 1, // 取设备状态正常的数据
        }
        let equDataList = await EquipmentModel.find(equQuery, "_id name type cordon wafer_uid").lean();

        let logProAll = equDataList.map(async (item, index) => {
            let logQuery = {
                status: 1,
                equipment_id: item._id,
                real_num: {$lt: 6500}
            }
            let logData = await EquipmentLogModel.find(logQuery).sort({_id: -1}).limit(20).lean();
            item.logData = logData.map(logItem => {
                return {
                    value: logItem.real_num,
                    label: moment(logItem.create_at).format("hh:mm:ss")
                }
            })
        })

        await Promise.all(logProAll);

        return koaTool.success(ctx, koaTool.msg.SUCCESS, equDataList)

    }

}

module.exports=new RptController()